package com.ljy.my_study.leetcode.四数之和;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TestMain2 {

    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result=new ArrayList<>();
        Arrays.sort(nums);
        for(int i=0;i<nums.length-3;i++){
            if(i>0&&nums[i]==nums[i-1]){
                continue;
            }
            for(int j=i+1;j<nums.length-2;j++){
                if(j>i+1&&nums[j]==nums[j-1]){
                    continue;
                }
                int left=j+1;
                int right=nums.length-1;
                int sum=nums[i]+nums[j];
                while(left<right){
                    int allSum=sum+nums[left]+nums[right];
                    if(allSum<target){
                        left++;
                    }else if(allSum>target){
                        right--;
                    }else{
                        checkAndAddList(result,Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
                        left++;
                        right--;
                    }
                }
            }
        }
        return result;
    }

    private void checkAndAddList(List<List<Integer>> result, List<Integer> list){
        int len=result.size();
        if(len==0){
            result.add(list);
        }else{
            List<Integer> lastList=result.get(len-1);
            boolean same=true;
            for(int i=0;i<lastList.size();i++){
                if(!lastList.get(i).equals(list.get(i))){
                    same=false;
                    break;
                }
            }
            if(!same){
                result.add(list);
            }
        }
    }
}
